package com.yilijk.base.utils;


import com.yilijk.base.network.RequestParams;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;

/**
 * 数据签名校验
 *
 * @author cenjunlei
 * @date 2021/10/14 14:14
 */
public class UrlSignUtils {

    private static final String SECRET_KEY = "0513ff1222f21dcebc3c689f1cbc509f";
    /**
     * 不参与签名的参数
     */
    private static final String[] FILTER = {"terminal"};

    public static JSONObject sign(JSONObject object) {



        try {
            object.put("timestamp", System.currentTimeMillis() / 1000);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        List<String> list = new ArrayList<>();
        Iterator<String> iterator = object.keys();
        while (iterator.hasNext()) {
            String key = iterator.next();

            if (key == null || Arrays.asList(FILTER).contains(key)) {
                continue;
            }
            list.add(key);
        }
        ALog.i(list.toString());

        Collections.sort(list, String::compareTo);

        RequestParams newObject = new RequestParams();
        for (String key : list) {
            newObject.put(key, object.opt(key));
        }

        String data = newObject.toString() + SECRET_KEY;
        String sign = EncryptUtils.encryptMD5ToString(data).toLowerCase(Locale.ROOT);

        try {
            object.put("sign", sign);
        } catch (JSONException e) {
            e.printStackTrace();
        }

//        ALog.i(path);
//        ALog.i(list);
//        ALog.i(data);
//        ALog.i(sign);
        return object;
    }

}
